import {Component} from '@angular/core';
import {ModalController, NavController, Platform} from 'ionic-angular';
import {TabsPage} from "../tabs/tabs";
import {Md5} from "ts-md5/dist/md5";
import {BackButtonService} from "../../services/backButton.service";
import {AppGlobal, AppService} from "../../services/app.service";
import {Storage} from "@ionic/storage";
import {ResDataModel} from "../../models/res-data-model";
import {SysDictService} from "../../services/sysDict.service";
// import { Storage } from "@ionic/storage";
// import {FormBuilder} from "@angular/forms";
// import {JPush} from "@jiguang-ionic/jpush";
/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
declare var BMap;
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  userCode: string = '';
  password: string = '';
  device:any;
  // latitude:string;//维度
  // longitude:string;//经度


  constructor(public modalCtrl: ModalController,
              private nav: NavController,
              // private http: HttpClient,
              private appService: AppService,
              private backButtonService: BackButtonService,
              private sysDictService:SysDictService,
              private storage:Storage,
              private platform: Platform) {
    //从缓存中获取设备信息
    this.storage.get('device').then((value)=>{
      if(value){//存在
        this.device = value;
      } else {//不存在
        this.device = {
          uuid: "ad09e2decdfaa70d",
          serial: "427df3c8",
          platform: "Android",
          version: "7.1.1",
          model: "NX563J",
          manufacturer: "nubia",
          cordova: "6.1.2",
          isVirtual: false
        }
      }
      console.log(this.device);
    })


    var geoLocation = new BMap.Geolocation();
    geoLocation.getCurrentPosition(function(r){
      if(this.getStatus() == 0){
        AppGlobal.longitude = r.point.lng;
        AppGlobal.latitude = r.point.lat;
      }
      else {
        alert('failed'+this.getStatus());
      }
    },{enableHighAccuracy: true});


    this.platform.ready().then(() => {
      this.backButtonService.registerBackButtonAction(null);
    });
  }

  logIn() {
/*      this.sysDictService.getDictsByDictTypeCode('jjcd').then(data=>{
          alert(JSON.stringify(data));
      },err=>{
          alert(JSON.stringify(err));
      }).catch(err=>{
          alert(JSON.stringify(err));
      });*/

    //let userinfo: string = '用户名：' + username.value + '密码：' + Md5.hashStr(password.value);
    if (this.userCode.length == 0) {
      this.appService.toast("请输入账号");
    } else if (this.password.length == 0) {
      this.appService.toast("请输入密码");
    } else {
      //网络请求
      let postData = {
          userName:this.userCode,
          password:Md5.hashStr(this.password),
          position:{
            lng:AppGlobal.longitude.toString(),
            lat:AppGlobal.latitude.toString()
          },
          device:this.device
        };

      this.appService.httpPost('AppLoginCtrl_login',postData,null,(res:ResDataModel) => {
        console.log(res.datas);
        let flag = res.getAttr('flag');
        if(flag == 'success') {//登录成功
          //记下token
          let token = res.getAttr('token')
          this.storage.set('token',token);
          AppGlobal.token = token;
          //记下功能列表
          AppGlobal.menus = res.getDataList('gnlb');
          //密码清空
          this.password = '';
          //跳转首页
          this.nav.setRoot(TabsPage);

        } else {//登录失败
          this.appService.alert('登录失败');
        }

      },true);
      // this.navCtrl.push(TabsPage);
    }
  }

  logInTemp() {
    //直接跳过登录访问首页
    // let modal = this.modalCtrl.create(TabsPage);
    // modal.present();

    this.appService.smallToast('test','error');
    //测试https
    // this.appService.httpGet('','',(res) => {
    //   console.log(res);
    // })
  }

  getLocation(){
    if (navigator.geolocation){
      navigator.geolocation.getCurrentPosition(this.showPosition,this.showError);
    }else{
      alert("浏览器不支持地理定位。");
    }
  }

  showPosition(position){
    var lat = position.coords.latitude; //纬度
    var lag = position.coords.longitude; //经度
    alert('纬度:'+lat+',经度:'+lag);
  }

  showError(error){
    switch(error.code) {
      case error.PERMISSION_DENIED:
        alert("定位失败,用户拒绝请求地理定位");
        break;
      case error.POSITION_UNAVAILABLE:
        alert("定位失败,位置信息是不可用");
        break;
      case error.TIMEOUT:
        alert("定位失败,请求获取用户位置超时");
        break;
      case error.UNKNOWN_ERROR:
        alert("定位失败,定位系统失效");
        break;
    }
  }

  /**
   * 跳转到注册页面
   */
  toSendMailPage(){
    this.nav.push('SendMailPage');
  }

  /**
   * 跳转忘记密码页
   */
  toGetIdentifyingCodePage(){
    this.nav.push('GetIdentifyingCodePage',{device:this.device,login:true});
  }

  ionViewDidLoad() {
  }

}
